﻿namespace DimensionsHelper.Client.WinUi.Views;

public partial class ItemsPageBase : Page, INotifyPropertyChanged
{
    private string? _itemTypeName;


    public IEnumerable<PageInfo>? Items
    {
        get => field;
        set => SetProperty(ref field, value);
    }

    public event PropertyChangedEventHandler? PropertyChanged;


    protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
    {
        if (Equals(field, value))
        {
            return false;
        }

        field = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        return true;
    }


    protected void OnItemGridViewItemClick(object sender, ItemClickEventArgs e)
    {
        PageInfo pageInfo = (PageInfo)e.ClickedItem;
        _itemTypeName = pageInfo.FullTypeName;
        App.GetService<INavigationService>().NavigateTo(_itemTypeName);
    }


    protected void OnItemGridViewLoaded(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(_itemTypeName) || sender is not GridView gridView)
        {
            return;
        }

        if (gridView.ItemsSource is IEnumerable<PageInfo> items &&
            items.FirstOrDefault(info => info.Id == _itemTypeName) is { } pageInfo)
        {
            gridView.ScrollIntoView(pageInfo);
            ((GridViewItem)gridView.ContainerFromItem(pageInfo))?.Focus(FocusState.Programmatic);
        }
    }
}